package com.netx.generics.io;
import java.io.IOException;
import com.netx.generics.basic.Context;
import com.netx.generics.basic.Property;
import com.netx.generics.basic.PropertySetListener;
import com.netx.generics.basic.ObjectAlreadyExistsException;
import com.netx.generics.io.FileSystem;


public class FsContext extends Context {

	public FsContext() {
		super("filesystems", Context.getRootContext());
		addPropertySetListener(new Listener());
	}
	
	public FileSystem getFS(String name) throws IOException {
		Property p = getProperty(name);
		if(p == null) {
			return null;
		}
		else {
			if(p.objectValue() instanceof Location) {
				p = new Property(p.getName(), new FileSystem((Location)p.objectValue()));
				setProperty(p);
			}
			// FileSystem loaded:
			return (FileSystem)p.objectValue();
		}
	}
	
	private class Listener implements PropertySetListener {
		public Listener() {
		}
		
		public void onBeforeSet(Property p, Context c) {
			if(c.getProperty(p.getName()) != null) {
				throw new ObjectAlreadyExistsException(p.getName());
			}
			if(p.objectValue() instanceof Location) {
				return;
			}
			if(p.objectValue() instanceof FileSystem) {
				return;
			}
			throw new IllegalArgumentException("illegal class for property '"+p.getName()+": "+p.objectValue().getClass().getName());
		}
		
		public void onAfterSet(Property p, Context c) {
			// noop;
		}
	}
}
